﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace SerializationStudy
{
    class InterfaceSerializable
    {
        public static void Test()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                var formater = new BinaryFormatter();
                formater.Serialize(stream, new TestClassB() { X = 5 });

                stream.Position = 0;

                var test = formater.Deserialize(stream) as TestClassB;

                Console.WriteLine(test.X);
            }
        }
    }

    [Serializable]
    public sealed class TestClassB : ISerializable, IDeserializationCallback
    {
        public int X;

        public TestClassB()
        {
        }

        private TestClassB(SerializationInfo info, StreamingContext context)
        {
            X = info.GetInt32("X");
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("X", X);
        }

        [OnSerializing]
        private void OnSerializing(StreamingContext context)
        {
            Console.WriteLine("TestClassB OnSerializing");
        }

        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
            Console.WriteLine("TestClassB OnSerialized");
        }

        [OnDeserializing]
        private void OnDeserializing(StreamingContext context)
        {
            Console.WriteLine("TestClassB OnDeserializing");
        }

        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            Console.WriteLine("TestClassB OnDeserialized");
        }

        public void OnDeserialization(object sender)
        {
            Console.WriteLine("TestClassB OnDeserialization");
        }
    }
}
